<?php

class LoginController extends Zend_Controller_Action
{

    public function init()
    {

    }

    public function indexAction()
    {
		$req = $this->getRequest();
		if ($req->isGet()){
			$url = $req->get('rurl');
			$url = empty($url) ? '/' : $url;
			$auth = new Application_Model_Auth();
			if($auth->isLoggedIn()){
				$this->_redirect($url);
			}
			$this->view->rurl = array_key_exists('HTTP_REFERER', $_SERVER) ? $_SERVER['HTTP_REFERER']:$url;
			
			$this->view->captchaId='';
			$captcha = $this->getCaptchaObj();
			$captchaid = $captcha->getImgUrl().$captcha->getId().$captcha->getSuffix();
			$session =new Zend_Session_Namespace('code');
			$session->captcha =$captcha->getWord();
			if($req->isXmlHttpRequest()){ 
				$tag=$req->get('tag');
				if($tag=='changeCaptcha'){
					echo json_encode(array('msg'=>$captchaid));
					exit;
				}
			}
			$this->view->captchaId = $captchaid;
			
		} else if ($req->isPost() && $req->isXmlHttpRequest()){
			$type = $req->getPost('type');
			$this->view->rurl = $req->getPost('rurl');
			$phone = $req->getPost('phone');
			
			if($type=="send"){
				if(empty($phone)||strlen($phone) < 11) {
					echo json_encode(array('msg'=>'phoneError'));
					exit;
				} else{
					$rest = new Application_Model_Rest();
					$res = $rest->getCaptcha($phone);
					if(empty($res)){
						echo json_encode(array('msg'=>'getFailed'));
						exit;
					}
					$amount = $res[0]->amount;
					echo json_encode(array('msg'=>$phone,'amount'=>$amount));
					exit;
				}
			}else{//login
				$captcha = $req->getPost('captcha');
				$phone = $req->getPost('phone');
				$code = $req->getPost('code');
				$verify = $req->getPost('verify');
				$rurl = $req->getPost('rurl');
				if(empty($captcha)||empty($phone)){
					echo json_encode(array('msg'=>'paraNull'));
					exit;
				}
				$auth = new Application_Model_Auth();
				if(!$auth->authorise($phone,$captcha,$verify,$code)) {
					echo json_encode(array('msg'=>'captchaWrong'));
					exit;
				}
				echo json_encode(array('msg'=>'success','rurl'=>$rurl));
				exit;
			}
			
			$this->view->phone = $phone;
		}
    }

    public function captchaAction()
    {
		
    }
	
	protected function getCaptchaObj(){
		$captcha = new Zend_Captcha_Image();
        $captcha->setTimeout('10')
        ->setWordLen('4')
        ->setFontSize('26')
        ->setHeight('45')                
        ->setWidth('100')                
        ->setDotNoiseLevel('40')                
        ->setLineNoiseLevel('5')                
        ->setFont('t1.ttf');
		
        $captcha->setExpiration(5);
        $captcha->setGcFreq(1);
        $captcha->generate();
		return $captcha;
	}
}
?>


